package com.unittec.zk.provider.auth.excel.imports;

import java.util.Map;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Service;

import com.rabbitmq.client.Channel;
import com.unittec.zk.provider.common.RabbitConstants;
import com.unittec.zk.provider.log.Log;
import com.unittec.zk.provider.scope.ThreadLocalScope;
import com.unittec.zk.sdk.auth.request.Req101921;
import com.unittec.zk.sdk.root.internal.utils.SdkUtils;

/**
 * @Description: EXCEL导入异步消费方法
 * @Author: wuxinwei
 * @CreateDate: 2019/11/19 13:39
 */
@Service
@RabbitListener(queues = RabbitConstants.QUEUE_IMPORT_EXCEL)
public class MqExcelImportConsumerService {

    @Autowired
    private Log log;

    @Autowired
    private ExcelImportService excelImportService;

    /**
     * 入库
     *
     * @param content
     * @param channel
     * @param deliveryTag
     * @param redelivered
     * @param head
     */

    @RabbitHandler
    public void process(Req101921 content, Channel channel, @Header(name = "amqp_deliveryTag") long deliveryTag,
        @Header("amqp_redelivered") boolean redelivered, @Headers Map<String, String> head) {
        try {
            // 监听消息队列中的数据，不能用拦截器中的公共数据，plus的多租户特性不能自己设置属性，这里特殊处理下
            ThreadLocalScope.setAuthData(content.getRequestId(), content.getToken(), content.getAppId(),
                content.getTenantId(), content.getIp(), content.getUser(), content.getAppCode(), content.getUserName());
            excelImportService.importExcelAsync(content.getImportTaskId(), content.getConsumer(), content.getFilePath(),
                content.getFileName(), content.getType(), content.getParamMap());
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.sysErrLog("101921", SdkUtils.toJSON(content), e);
            // 一般重试肯定的有次数，这里简单的根据是否已经重发过来来决定重发。第二个参数表示是否重新分发
            try {
                channel.basicReject(deliveryTag, !redelivered);
            } catch (Exception e1) {

            }
        }
    }
}
